package juc.work;

/**
 * 非继承Executor线程池实现，适合手撕
 */
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class SimpleThreadPool {
    private final BlockingQueue<Runnable> taskQueue;
    private final int maxThreads;
    private final Thread[] threads;
    private boolean isShutdown = false;

    public SimpleThreadPool(int maxThreads) {
        this.maxThreads = maxThreads;
        this.taskQueue = new LinkedBlockingQueue<>();
        this.threads = new Thread[maxThreads];
        for (int i = 0; i < maxThreads; i++) {
            threads[i] = new WorkerThread();
            threads[i].start();
        }
    }

    public void execute(Runnable task) {
        if (isShutdown) throw new IllegalStateException("ThreadPool is shutdown");
        try {
            taskQueue.put(task);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    public void shutdown() {
        isShutdown = true;
        for (Thread thread : threads) {
            thread.interrupt();
            thread = null;
        }
    }

    private class WorkerThread extends Thread {
        @Override
        public void run() {
            while (!isShutdown) {
                try {
                    Runnable task = taskQueue.take();
                    task.run();
                } catch (InterruptedException e) {
                    if (isShutdown) return;
                    Thread.currentThread().interrupt();
                }
            }
        }
    }
}
